<template>
  <view class="openid-container">
    <view class="header">
      <image class="logo" src="/static/logo.png" mode="aspectFit"></image>
      <text class="title">授权确认</text>
      <text class="subtitle">为配送员提供分账服务支持</text>
    </view>

    <view class="content">
      <view class="info-card">
        <view class="icon">🔐</view>
        <view class="info-text">
          <text class="main-text">正在为您的配送员授权</text>
          <text class="sub-text">此操作用于支持微信支付分账功能，确保配送费用能够正确分配给配送员</text>
        </view>
      </view>

      <view class="progress" v-if="loading">
        <view class="progress-bar">
          <view class="progress-fill" :style="{ width: progress + '%' }"></view>
        </view>
        <text class="progress-text">{{ progressText }}</text>
      </view>

      <view class="result" v-if="!loading">
        <view class="result-icon" :class="{ success: isSuccess, error: !isSuccess }">
          {{ isSuccess ? '✓' : '✗' }}
        </view>
        <text class="result-text">{{ resultText }}</text>
        <button class="return-btn" @click="returnToDelivery" v-if="isSuccess">
          返回配送端
        </button>
        <button class="retry-btn" @click="retryAuth" v-if="!isSuccess">
          重试授权
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { saveCustomerOpenidToDeliverUser } from '@/api/wechat'

// 响应式数据
const loading = ref(true)
const progress = ref(0)
const progressText = ref('正在获取授权...')
const isSuccess = ref(false)
const resultText = ref('')
const deliveryOpenid = ref('')

/**
 * 页面加载时处理 - 获取页面参数
 */
onLoad((options) => {
  deliveryOpenid.value = options.deliveryOpenid
  
  if (deliveryOpenid.value) {
    // 页面参数获取成功，等待页面挂载完成后开始授权
    console.log('获取到配送员openid:', deliveryOpenid.value)
  } else {
    showError('参数错误，请重新操作')
  }
})

/**
 * 页面挂载完成后开始授权流程
 */
onMounted(() => {
  if (deliveryOpenid.value) {
    startAuth()
  }
})

/**
 * 开始授权流程
 */
const startAuth = async () => {
  try {
    // 模拟进度更新
    updateProgress(20, '正在获取微信授权...')
    
    // 获取微信登录code
    const loginResult = await getWechatLoginCode()
    updateProgress(60, '正在保存授权信息...')
    
    // 调用后端接口保存openid
    await saveCustomerOpenid(loginResult.code)
    updateProgress(100, '授权完成')
    
    // 延迟显示成功结果
    setTimeout(() => {
      showSuccess('授权成功！即将返回配送端')
    }, 500)
    
  } catch (error) {
    console.error('授权失败:', error)
    showError('授权失败，请重试')
  }
}

/**
 * 获取微信登录code
 */
const getWechatLoginCode = () => {
  return new Promise((resolve, reject) => {
    uni.login({
      provider: 'weixin',
      success: resolve,
      fail: reject
    })
  })
}

/**
 * 保存顾客端openid
 */
const saveCustomerOpenid = async (code) => {
  try {
    await saveCustomerOpenidToDeliverUser({
      code: code,
      deliveryOpenid: deliveryOpenid.value
    })
  } catch (error) {
    throw new Error('保存openid失败')
  }
}

/**
 * 更新进度
 */
const updateProgress = (value, text) => {
  progress.value = value
  progressText.value = text
}

/**
 * 显示成功结果
 */
const showSuccess = (text) => {
  loading.value = false
  isSuccess.value = true
  resultText.value = text
  
  // 3秒后自动返回配送端
  setTimeout(() => {
    returnToDelivery()
  }, 3000)
}

/**
 * 显示错误结果
 */
const showError = (text) => {
  loading.value = false
  isSuccess.value = false
  resultText.value = text
}

/**
 * 返回配送端小程序
 */
const returnToDelivery = () => {
  uni.navigateBackMiniProgram({
    success: () => {
      console.log('返回配送端成功')
    },
    fail: (err) => {
      console.error('返回配送端失败:', err)
      uni.showToast({
        title: '返回失败，请手动切换',
        icon: 'none'
      })
    }
  })
}

/**
 * 重试授权
 */
const retryAuth = () => {
  loading.value = true
  progress.value = 0
  startAuth()
}
</script>

<style lang="scss" scoped>
.openid-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 60rpx 40rpx;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 80rpx;
  margin-bottom: 80rpx;

  .logo {
    width: 120rpx;
    height: 120rpx;
    margin-bottom: 30rpx;
    border-radius: 30rpx;
    box-shadow: 0 8rpx 32rpx rgba(255, 255, 255, 0.2);
  }

  .title {
    font-size: 44rpx;
    font-weight: 600;
    color: #fff;
    margin-bottom: 16rpx;
    letter-spacing: 2rpx;
  }

  .subtitle {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
    text-align: center;
    line-height: 1.4;
  }
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.info-card {
  width: 100%;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 24rpx;
  padding: 40rpx;
  margin-bottom: 60rpx;
  display: flex;
  align-items: flex-start;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);

  .icon {
    font-size: 48rpx;
    margin-right: 24rpx;
    margin-top: 8rpx;
  }

  .info-text {
    flex: 1;

    .main-text {
      display: block;
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 16rpx;
    }

    .sub-text {
      display: block;
      font-size: 26rpx;
      color: #666;
      line-height: 1.5;
    }
  }
}

.progress {
  width: 100%;
  margin-bottom: 40rpx;

  .progress-bar {
    width: 100%;
    height: 8rpx;
    background: rgba(255, 255, 255, 0.3);
    border-radius: 4rpx;
    overflow: hidden;
    margin-bottom: 20rpx;

    .progress-fill {
      height: 100%;
      background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
      border-radius: 4rpx;
      transition: width 0.3s ease;
    }
  }

  .progress-text {
    display: block;
    text-align: center;
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.9);
  }
}

.result {
  display: flex;
  flex-direction: column;
  align-items: center;

  .result-icon {
    width: 120rpx;
    height: 120rpx;
    border-radius: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 60rpx;
    font-weight: bold;
    margin-bottom: 30rpx;

    &.success {
      background: #4caf50;
      color: #fff;
    }

    &.error {
      background: #f44336;
      color: #fff;
    }
  }

  .result-text {
    font-size: 32rpx;
    color: #fff;
    text-align: center;
    margin-bottom: 40rpx;
    line-height: 1.4;
  }

  .return-btn,
  .retry-btn {
    width: 300rpx;
    height: 80rpx;
    border-radius: 40rpx;
    font-size: 30rpx;
    font-weight: 500;
    border: none;
    color: #fff;

    &.return-btn {
      background: linear-gradient(135deg, #4caf50 0%, #45a049 100%);
    }

    &.retry-btn {
      background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
    }

    &:active {
      opacity: 0.8;
    }
  }
}
</style>